import React, { useState, useEffect, useContext } from 'react';
import { NavBar, Toast, Modal, Form, Input, Popover, SearchBar } from 'antd-mobile';
import { UserAddOutlined, UserOutlined, UsergroupAddOutlined, VideoCameraAddOutlined, LockOutlined, ClearOutlined, SendOutlined, PlusOutlined } from '@ant-design/icons';
import { observer } from "mobx-react-lite";

import { useHistory } from "react-router-dom";
import MessageChannelBar from '../../../components/MessageChannelBar';
import SelectSingleContactor from '../../../components/SelectSingleContactor';
import SelectGroupContactor from '../../../components/SelectGroupContactor';
import ConversationList from './ConversationList';
import ConversationListByGroup from './ConversationListByGroup';

import { MySdkStoreContext } from '../../../context';
import { CUSTOM_LAYOUT_STORAGE_KEY, SettingSwitchKeys } from '../../../constants';

import './style.scss';

const ConverList = observer((props) => {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const [addUserForm] = Form.useForm();
  const [setGroupNameForm] = Form.useForm();

  const myUserId = mySdkStore.mockConfig.userId;
  const [selectSingleContactorProps, setSelectSingleContactorProps] = useState({ visible: false });
  const [selectGroupContactorProps, setSelectGroupContactorProps] = useState({ visible: false });
  const [isConversationGroupMode, setIsConversationGroupMode] = useState(false);

  // 获取“是否开启聊天分组模式”数据
  useEffect(() => {
    const setting = localStorage.getItem(CUSTOM_LAYOUT_STORAGE_KEY);
    if (setting) {
      try {
        setIsConversationGroupMode(JSON.parse(setting)[SettingSwitchKeys.conversationGroup]??false);
      } catch (e) {
        console.log(e);
      }
    }
  }, []);

  // 顶部“+”菜单
  const popoverItem = [
    { key: 'addUser', icon: <UserAddOutlined style={{ marginRight: 15 }} />, text: '添加好友', },
    { key: 'createConversation', icon: <UserOutlined style={{ marginRight: 15 }} />, text: '发起单聊' },
    { key: 'createGroupConversation', icon: <UsergroupAddOutlined style={{ marginRight: 15 }} />, text: '发起群聊' },
    { key: 'createMeeting', icon: <VideoCameraAddOutlined style={{ marginRight: 15 }} />, text: '发起会议', },
    // { key: 'createChattingRoom', icon: <DesktopOutlined style={{ marginRight: 15 }} />, text: '创建聊天室', },
    // { key: 'createSecretConversation', icon: <LockOutlined style={{ marginRight: 15 }} />, text: '发起密聊' },
    { key: 'sendMessageByBatch', icon: <SendOutlined style={{ marginRight: 15, transform: 'rotate(-45deg)' }} />, text: '群发消息' },
  ];

  // “+”菜单点击“添加好友”事件
  const handleAddUser = () => {
    Modal.confirm({
      title: '添加好友',
      content: <Form form={addUserForm}>
        <Form.Item name="invitedUserId" label={null} rules={[{ required: true, message: '请输入用户ID'}]}>
          <Input placeholder="请输入用户ID" />
        </Form.Item>
      </Form>,
      onConfirm: () => new Promise(async (resolve, reject) => {
        try {
          const values = await addUserForm.validateFields();
          await mySdkStore.sdk.addFriend({ ...values });
          Toast.show('好友请求已发送');
          resolve(true);
        } catch(e: any) {
          if (e.errorMessage) {
            Toast.show(e.errorMessage);
          }
          reject();
        }
      }),
    });
  };

  // “+”菜单点击“发起群聊”事件
  const handleCreateGroupConversation = () => {
    setSelectGroupContactorProps({
      visible: true,
      title: '选择对象',
      cid: '',
      getListApi: 'queryUsers',
      listFilterFunc: (list) => list.filter(item => item.id !== myUserId),
      onOk: async (userIds) => {
        Modal.confirm({
          title: '设置群名称',
          content: <Form form={setGroupNameForm}>
            <Form.Item name="name" label={null} rules={[{ required: true, message: '请输入群名称'}]}>
              <Input maxlength={10} placeholder="请输入群名称" />
            </Form.Item>
          </Form>,
          onConfirm: () => new Promise(async (resolve, reject) => {
            try {
              const values = await setGroupNameForm.validateFields();
              const { cid } = await mySdkStore.sdk.createConversation({ type: 'group', name: values.name, owner: mySdkStore.mockConfig.userId, members: userIds, subUserId: userIds })
              history.push({ pathname: `/chatDetail/${cid}` });
              setSelectGroupContactorProps({ visible: false });
              resolve(true);
            } catch(e: any) {
              if (e.errorMessage) {
                Toast.show(e.errorMessage);
              }
              reject();
            }
          })
        });
      },
      onClose: () => setSelectGroupContactorProps({ visible: false})
    });
  };

  // “+”菜单点击“发起单聊”事件
  const handleCreateConversation = () => {
    setSelectSingleContactorProps({
      visible: true,
      title: '选择对象',
      cid: '',
      getListApi: 'queryUsers',
      onOk: (userId, userInfo) => {
        mySdkStore.sdk.createConversation({ type: 'single', subUserId: userId, name: userInfo.userName, logoURL: userInfo.avatarUrl }).then((data) => {
          history.push({ pathname: `/chatDetail/${data.cid}` });
        }, () => {
          Toast.show('创建单聊失败')
        });
      },
      onClose: () => setSelectSingleContactorProps({ visible: false})
    });
  };

  const handleCreateMeeting = () => {
    history.push({ pathname: `/createMeeting` });
  }

  const handleCreateChattingRoom = () => {

  }

  const handleCreateSecretConversation = () => {

  }

  // “+”菜单点击“群发消息”事件
  const handleSendMessageByBatch = () => {
    history.push('/sendMessageByBatch');
  }

  const handleMenu = (e) => {
    switch(e.key) {
      case 'addUser':
        handleAddUser();
        break;

      case 'createConversation':
        handleCreateConversation();
        break;

      case 'createGroupConversation':
        handleCreateGroupConversation();
        break;

      case 'createMeeting':
        handleCreateMeeting();
        break;

      case 'createChattingRoom':
        handleCreateChattingRoom();
        break;

      case 'createSecretConversation':
        handleCreateSecretConversation();
        break;

      case 'sendMessageByBatch':
        handleSendMessageByBatch();
        break;
    }
  }

  return (
    <div className="chatListPage">
    <div className='converContent'>
      <NavBar
        back={null}
        style={{ background: '#fff', border: 'none' }}
        right={
          <Popover.Menu
            actions={popoverItem}
            placement='topRight'
            onAction={handleMenu}
            trigger='click'
          >
            <PlusOutlined style={{ color: 'rgba(0,0,0,.65)', fontSize: 20 }}/>
          </Popover.Menu>
      }>
        消息
      </NavBar>
      { !mySdkStore.isHideSomeFunctions && <SearchBar placeholder="搜索" className="searchBar" onFocus={() => history.push({ pathname: '/globalSearch'}) }  /> }
      { mySdkStore.isHideSomeFunctions ? null : <MessageChannelBar sdk={mySdkStore.sdk} mySdkStore={mySdkStore}/> }
      { !isConversationGroupMode ? <ConversationList {...props} /> : <ConversationListByGroup {...props} /> }
      </div>
    { selectSingleContactorProps.visible && <SelectSingleContactor {...selectSingleContactorProps} /> }
    { selectGroupContactorProps.visible && <SelectGroupContactor {...selectGroupContactorProps} /> }
  </div>)
})

export default ConverList;